package cn.cttic.link.util;

import jakarta.servlet.http.HttpServletRequest;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.URI;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class HttpClientUtil {

    private static Logger log = LoggerFactory.getLogger(HttpClientUtil.class);

    public static String getRequestBody(HttpServletRequest request) {
        try {
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuilder responseStrBuilder = new StringBuilder();
            String inputStr;

            while ((inputStr = streamReader.readLine()) != null) {
                responseStrBuilder.append(inputStr);
            }

            return responseStrBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 封装HTTP POST方法
     *
     * @param
     * @param
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String get(String url, Map<String, String > paramMap) throws ClientProtocolException, IOException {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        /** 忽略SSL证书校验*/
        try {
            //Secure Protocol implementation.
            SSLContext ctx = SSLContext.getInstance("SSL");
            //Implementation of a trust manager for X509 certificates
            X509TrustManager tm = new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] xcs,
                                               String string) throws CertificateException {
                }

                public void checkServerTrusted(X509Certificate[] xcs,
                                               String string) throws CertificateException {
                }

                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            ctx.init(null, new TrustManager[]{tm}, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
            ClientConnectionManager ccm = httpClient.getConnectionManager();
            //register https protocol in httpclient's scheme registry
            SchemeRegistry sr = ccm.getSchemeRegistry();
            sr.register(new Scheme("https", 443, ssf));

            URIBuilder builder = new URIBuilder(url);
            if (paramMap != null) {
                for (String key : paramMap.keySet()) {
                    builder.addParameter(key, paramMap.get(key));
                }
            }

            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);
            HttpResponse response = httpClient.execute(httpGet);
            String httpEntityContent = getHttpEntityContent(response);
            httpGet.abort();
            return httpEntityContent;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 封装HTTP POST方法
     *
     * @param
     * @param （如JSON串）
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String get(String url) throws ClientProtocolException, IOException {
        return get(url, null);
    }



    /**
     * 封装HTTP POST方法
     *
     * @param
     * @param
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String post(String url, Map paramMap) throws ClientProtocolException, IOException {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        /** 忽略SSL证书校验*/
        try {
            //Secure Protocol implementation.
            SSLContext ctx = SSLContext.getInstance("SSL");
            //Implementation of a trust manager for X509 certificates
            X509TrustManager tm = new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] xcs,
                                               String string) throws CertificateException {
                }

                public void checkServerTrusted(X509Certificate[] xcs,
                                               String string) throws CertificateException {
                }

                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            ctx.init(null, new TrustManager[]{tm}, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
            ClientConnectionManager ccm = httpClient.getConnectionManager();
            //register https protocol in httpclient's scheme registry
            SchemeRegistry sr = ccm.getSchemeRegistry();
            sr.register(new Scheme("https", 443, ssf));
        } catch (Exception e) {
            e.printStackTrace();
        }
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> formparams = setHttpParams(paramMap);
        UrlEncodedFormEntity param = new UrlEncodedFormEntity(formparams, HTTP.UTF_8);
        httpPost.setEntity(param);
        HttpResponse response = httpClient.execute(httpPost);
        String httpEntityContent = getHttpEntityContent(response);
        httpPost.abort();
        return httpEntityContent;
    }

    /**
     * 获得响应HTTP实体内容
     *
     * @param response
     * @return
     * @throws IOException
     * @throws UnsupportedEncodingException
     */
    private static String getHttpEntityContent(HttpResponse response) throws IOException, UnsupportedEncodingException {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream is = entity.getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String line = br.readLine();
            StringBuilder sb = new StringBuilder();
            while (line != null) {
                sb.append(line + "\n");
                line = br.readLine();
            }
            return sb.toString();
        }
        return "";
    }


    /**
     * 设置请求参数
     *
     * @param
     * @return
     */
    private static List<NameValuePair> setHttpParams(Map<String, String> paramMap) {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        Set<Map.Entry<String, String>> set = paramMap.entrySet();
        for (Map.Entry<String, String> entry : set) {
            formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        return formparams;
    }

    /**
     * 封装HTTP POST方法
     *
     * @param
     * @param （如JSON串）
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String post(String url, String data) throws ClientProtocolException, IOException {
        return post(url, data, true);
    }

    public static String post(String url, String data, boolean isencoder) throws ClientProtocolException, IOException {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
        if (isencoder) {
            httpPost.setEntity(new StringEntity(URLEncoder.encode(data, "UTF-8")));
        } else {
            httpPost.setEntity(new StringEntity(data));
        }
        HttpResponse response = httpClient.execute(httpPost);
        String httpEntityContent = getHttpEntityContent(response);
        httpPost.abort();
        return httpEntityContent;
    }

    public static String HQ_Post(String url, String data, boolean isencoder) throws ClientProtocolException, IOException {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
        if (isencoder) {
            httpPost.setEntity(new StringEntity(URLEncoder.encode(data, "UTF-8")));
        } else {
            httpPost.setEntity(new StringEntity(data, "UTF-8"));
        }

        log.info("环球上送报文: " + data);

        HttpResponse response = httpClient.execute(httpPost);
        String httpEntityContent = getHttpEntityContent(response);
        httpPost.abort();

        log.info("环球接收报文: " + httpEntityContent);

        return httpEntityContent;
    }

    public static String HQ_Form_Post(String url, Map param) throws ClientProtocolException, IOException {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        List<NameValuePair> formparams = setHttpParams(param);
        UrlEncodedFormEntity data = new UrlEncodedFormEntity(formparams, HTTP.UTF_8);
        httpPost.setEntity(data);
        log.info("环球上送报文: " + data);

        HttpResponse response = httpClient.execute(httpPost);
        String httpEntityContent = getHttpEntityContent(response);
        httpPost.abort();

        log.info("环球接收报文: " + httpEntityContent);

        return httpEntityContent;
    }


    public static String LXCJ_Form_Post(String url, Map param) throws ClientProtocolException, IOException {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        List<NameValuePair> formparams = setHttpParams(param);
        UrlEncodedFormEntity data = new UrlEncodedFormEntity(formparams, HTTP.UTF_8);
        httpPost.setEntity(data);
        log.info("<联合畅捷> 上送报文: " + data);

        HttpResponse response = httpClient.execute(httpPost);
        String httpEntityContent = getHttpEntityContent(response);
        httpPost.abort();

        log.info("<联合畅捷> 接收报文: " + httpEntityContent);

        return httpEntityContent;
    }

    /**
     * Application/JSON - POST 传输
     *
     * @param url
     * @param data
     * @param isencoder
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String JSON_Header_Post(String url, String data, Map<String, String> headers, boolean isencoder) throws ClientProtocolException, IOException {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
        for (String headerKey : headers.keySet()) {
            httpPost.setHeader(headerKey, headers.get(headerKey));
        }
        if (isencoder) {
            httpPost.setEntity(new StringEntity(URLEncoder.encode(data, "UTF-8")));
        } else {
            httpPost.setEntity(new StringEntity(data, "UTF-8"));
        }

        log.info("[Application/URL] 请求地址: " + url);
        log.info("[Application/JSON] 上送报文: " + data);

        HttpResponse response = httpClient.execute(httpPost);
        String httpEntityContent = getHttpEntityContent(response);
        httpPost.abort();

        log.info("[Application/JSON] 接收报文: " + httpEntityContent);

        return httpEntityContent;
    }


    /**
     * Application/JSON - POST 传输
     *
     * @param url
     * @param data
     * @param isencoder
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String JSON_Post(String url, String data, boolean isencoder) throws ClientProtocolException, IOException {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
        if (isencoder) {
            httpPost.setEntity(new StringEntity(URLEncoder.encode(data, "UTF-8")));
        } else {
            httpPost.setEntity(new StringEntity(data, "UTF-8"));
        }

        log.info("[Application/JSON] 上送报文: " + data);

        HttpResponse response = httpClient.execute(httpPost);
        String httpEntityContent = getHttpEntityContent(response);
        httpPost.abort();

        log.info("[Application/JSON] 接收报文: " + httpEntityContent);

        return httpEntityContent;
    }

    public static String Form_Post(String url, Map<String, String> param, boolean isencoder) throws ClientProtocolException, IOException {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

        StringBuffer sbParams = new StringBuffer();
        if (param != null && param.size() > 0) {
            for (Map.Entry<String, String> e : param.entrySet()) {
                sbParams.append(e.getKey());
                sbParams.append("=");
                sbParams.append(e.getValue());
                sbParams.append("&");
            }
        }
        String urlParams = sbParams.toString().substring(0, sbParams.length() - 1);
        httpPost.setEntity(new StringEntity(urlParams));
        log.info("[Application/FORM] 上送报文: " + urlParams);

        HttpResponse response = httpClient.execute(httpPost);
        String httpEntityContent = getHttpEntityContent(response);
        httpPost.abort();

        log.info("[Application/FORM] 接收报文: " + httpEntityContent);

        return httpEntityContent;
    }

    public static String GYF_Form_Post(String url, Map param) throws ClientProtocolException, IOException {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        List<NameValuePair> formparams = setHttpParams(param);
        UrlEncodedFormEntity data = new UrlEncodedFormEntity(formparams, HTTP.UTF_8);
        httpPost.setEntity(data);
//        log.info("[工易付] 上送报文: " + data);

        HttpResponse response = httpClient.execute(httpPost);
        String httpEntityContent = getHttpEntityContent(response);
        httpPost.abort();

//        log.info("[工易付] 接收报文: " + httpEntityContent);

        return httpEntityContent;
    }


    public static String iHuyiPost(String url, Map param) throws ClientProtocolException, IOException {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=GBK");
        List<NameValuePair> formparams = setHttpParams(param);
        UrlEncodedFormEntity data = new UrlEncodedFormEntity(formparams, "GBK");
        httpPost.setEntity(data);

        log.info("[iHuyi 上送报文] : " + data.toString());
        log.info("[iHuyi 上送报文] : " + formparams.toString());

        HttpResponse response = httpClient.execute(httpPost);
        String httpEntityContent = getHttpEntityContent(response);
        httpPost.abort();

        log.info("[iHuyi 接收报文]: " + httpEntityContent);

        return httpEntityContent;
    }

}
